package com.weiyuwqj.controller.user;

import com.weiyuwqj.api.model.BasUserSecurity;
import com.weiyuwqj.api.model.BusAccountBank;
import com.weiyuwqj.api.service.*;
import com.weiyuwqj.api.constant.Constants;
import com.weiyuwqj.api.constant.Message;
import com.weiyuwqj.api.exception.CrowdException;
import com.weiyuwqj.api.model.BasUser;
import com.weiyuwqj.api.model.SysTempcode;
import com.weiyuwqj.api.util.DateUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.JwtUtils;
import com.weiyuwqj.api.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangyong on 2016/11/23.
 */
@Controller
@RequestMapping("/login")
public class UserLoginController {

    String key="RskqNRL0WSwwVYFbGWfu54/wNPdD0I1N9u+e1PbTZO3zbk/LV95JvePbewf4QPYmqJ9WG9zpLXvZ" +
            "kgK3nf4eXw==MGVlOWQzZWUtZGRkYy00YTNkLTgzZjEtNTgyNWVmZWFmNDk0";

    @Autowired
    BasUserService userService;

    @Autowired
    SysTempcodeService tempcodeService;

/*    @Autowired
    BasRaffleTicketService basRaffleTicketService;*/
    @Autowired
    BasUserSecurityService userSecurityService;
    @Autowired
    BusAccountBankService accountBankService;

    @RequestMapping(value = "")
     public Object login(){
        return "main/login";
    }

    @RequestMapping(value = "/quickLogin")
    public Object quickLogin(){
        return "main/quickLogin";
    }

    /**
     * 快捷登录
     * @param request
     * @param mobile  手机号码
     * @param mobileCode  手机验证码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/quickLogin", method = RequestMethod.POST)
    public Object doLogin(HttpServletRequest request,String mobile, String mobileCode){

        Long validPhoneExpiredTime = (Long) request.getSession().getAttribute("validPhoneExpiredTime");
        String validPhoneCode=request.getSession().getAttribute("validPhoneCode").toString();

        //发送短信
        Date now = new Date();
        long between = (now.getTime() - validPhoneExpiredTime) / 1000;

        if (!(validPhoneCode.equals(mobileCode))) {
            throw new CrowdException("user.register.randomCode.error");
        }
        if (between > Constants.VALIDATETIME) {
            throw new CrowdException("user.register.randomCode.timeout");
        }

        SysTempcode tempcode=tempcodeService.getByMobileAndCode(mobile, validPhoneCode);
        if(tempcode==null){
            throw new CrowdException("user.register.randomCode.error");
        }


        BasUser user=userService.getUserByMobile(mobile);
        if(user==null){
            throw new CrowdException("user.login.username.no_such_user");
        }else {
//            MobileConstants.validPhoneCode = "";
//            MobileConstants.validPhoneExpiredTime = null;
//            Map res=new HashMap();
//            res.put("userId", user.getId());
//            res.put("result","success");
//            res.put("regesterTime",DateUtils.formatDate(user.getAddtime()));
//            res.put("lastLoginTime",DateUtils.formatDate(logService.getLastLoginTime(user.getId()),"yyyy-MM-dd HH:mm:dd"));
//            user.setLastLoginTime(new Date());
//            user.setLastLoginIp(IpUtils.get());
//            userService.updateNotNull(user);
//            appClientService.updateOrInsert(user.getId(),clientId);
//            AbstractLogCreater logCreater = new AppLoginLogCreater();
//            logCreater.crate(user.getId(),IpUtils.get());
//            logCreater.setProperty();
//            logCreater.getLog().setResult(1);
//            logService.save(logCreater.getLog());
            user.setLastLoginTime(new Date());
            user.setLastLoginIp(IpUtils.get());
            userService.updateNotNull(user);

            request.getSession().setAttribute("basUser",user);
            request.getSession().setAttribute("userId",user.getId());

            request.getSession().removeAttribute("validPhoneExpiredTime");
            request.getSession().removeAttribute("validPhoneCode");
            return Message.OK;
        }
    }

    /**
     * 密码登录
     * @param mobile  手机号码
     * @param password  密码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/passwordLogin", method = RequestMethod.POST)
    public Object quickLogin(String mobile,String password,HttpServletRequest request){

        Map<String, Object> map = new HashMap<>();
        if(!StringUtils.isNull(mobile)){
            map.put("mobile", mobile);
        }
        if(!StringUtils.isNull(password)){
            map.put("password", password);
        }

        BasUser user=userService.getUserByUsernameAndPassword(mobile, password);
        if(null == user){
            throw new CrowdException("user.login.username_or_password.error");
        }else {
//            Date d = new Date();
//            d = DateUtils.addMonths(d, 1);
//            String token = JwtUtils.token(user.getId() + "", key, d);
//            Map res=new HashMap();
//            res.put("userId", user.getId());
//            res.put("userToken", token);
//            res.put("regesterTime",DateUtils.formatDate(user.getAddtime()));
//            res.put("lastLoginTime",DateUtils.formatDate(logService.getLastLoginTime(user.getId()),"yyyy-MM-dd HH:mm:dd"));
//            res.put("result","success");
//            user.setLastLoginTime(new Date());
//            user.setLastLoginIp(IpUtils.get());
//            userService.updateNotNull(user);
//            appClientService.updateOrInsert(user.getId(),clientId);
//            AbstractLogCreater logCreater = new AppLoginLogCreater();
//            logCreater.crate(user.getId(),IpUtils.get());
//            logCreater.setProperty();
//            logCreater.getLog().setResult(1);
//            logService.save(logCreater.getLog());

            user.setLastLoginTime(new Date());
            user.setLastLoginIp(IpUtils.get());
            userService.updateNotNull(user);

            request.getSession().setAttribute("userId",user.getId());
            request.getSession().setAttribute("basUser",user);
            return Message.OK;
        }
    }

    /**
     * 我要借款接口，判断是否登录
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/isLogin", method = RequestMethod.POST)
    public Object isLogin(HttpServletRequest request){
        Object userId = request.getSession().getAttribute("userId");
        if(userId == null){
            return Message.FAIL;
        }else {
            Integer id = Integer.parseInt(userId.toString());
            Map map = new HashMap();
            BasUser user=userService.selectByKey(id);
            if(user!=null){
                user.setPassword("");
                user.setSalt("");
                user.setMobile(StringUtils.getString(user.getMobile()));
            }

            BasUserSecurity security=userSecurityService.getOneByUserId(id);
            if(security != null){
                if(security.getRealnameStatus()==1){
                    security.setRealname(StringUtils.getString(security.getRealname()));
                    security.setIdentifyCard(StringUtils.getString(security.getIdentifyCard()));
                    security.setPaymentPassword("");
                }
            }
            //查询银行卡信息
            BusAccountBank busAccountBank = accountBankService.getOneByUserId(id);
            if(busAccountBank!=null){
                busAccountBank.setCardNo(StringUtils.getString(busAccountBank.getCardNo()));
            }

            map.put("result","success");
            map.put("user",user);
            map.put("security",security);
            map.put("bank",busAccountBank);
            return map;
        }
    }
}
